//
//  AYGlobal.swift
//  AYContext
//
//  Created by amg on 2021/4/2.
//

import Foundation
import SwiftyUserDefaults
import AYUtilCore
import AYNetWorkCore
import AYProConfig
import RxSwift
import Alamofire

extension DefaultsKeys {
    /// 缓存用户的主键id
    var userid: DefaultsKey<String> { .init("com.aoyuan.userid", defaultValue: "")}
    //缓存token
    var token: DefaultsKey<String> { .init("com.aoyuan.token", defaultValue: "")}
    
    var username: DefaultsKey<String> { .init("com.aoyuan.username", defaultValue: "")}
    
    var password: DefaultsKey<String> { .init("com.aoyuan.password", defaultValue: "")}
    
    var isrember: DefaultsKey<Bool> { .init("com.aoyuan.isrember", defaultValue: false)}
}

public struct AYGlobal {
    public static var shared = AYGlobal()
    private var disposeBag = DisposeBag()
    private init() { }
    
    public var user: AYUserModel?
    
    ///更新用户信息
    public static func updateUserModel(_ user:AYUserModel) -> Void {
        AYGlobal.shared.user = user
        Defaults[\.userid] = user.userid
        Defaults[\.token] = user.token
        updateToken()
        /// 发送退出通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: AYEnvs.notificationKey.loginSuccess), object: user)
    }
    
    /// 更新token
    public static func updateToken() {
        if let user = AYGlobal.shared.user {
            AYNetWorkAPI.sharedInstance.headers["token"] = user.token
        }
    }
    
    /// 退出登录 ， 清空用户信息
    public static func logout() {
        AYGlobal.shared.user  = nil
        Defaults.remove(\.userid)
        Defaults.remove(\.token)
        AYNetWorkAPI.sharedInstance.headers.removeValue(forKey: "token")
        /// 发送退出通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: AYEnvs.notificationKey.logoutSuccess), object: nil)
    }
    
    public static func isRember() -> Bool {
        return Defaults[\.isrember]
    }
    
    public static func updateIsRember( _ isRember:Bool) {
        Defaults[\.isrember] = isRember
    }
    
    public static func userName() -> String {
        return Defaults[\.username]
    }
    
    public static func updateUserName( _ userName:String) {
        Defaults[\.username] = userName
    }
    
    public static func password() -> String {
        return Defaults[\.password]
    }
    
    public static func updatePassword( _ password:String) {
        Defaults[\.password] = password
    }
    
    //在发起通过token获取用户对象之前，读取本地缓存的token然后更新header中的token
    static func updateHeaderTokenFromCache () {
        if let user = AYGlobal.shared.user {
            AYNetWorkAPI.sharedInstance.headers["token"] = user.token
        } else {
            let token = Defaults[\.token]
            if token.length > 0 {
                AYNetWorkAPI.sharedInstance.headers["token"] = token
            }
        }
    }
    
    //根据缓存的token更新用户对象
    public func updateUserFromService () {
        AYGlobal.updateHeaderTokenFromCache()
        Observable.just(GlobalApi.correctionuser)
            .emeRequestApiForObj(AYUserModel.self)
            .subscribe(onNext: { (result) in
                switch result {
                case .success(let user):
                    //登陆成功就更新上下文中的登陆对象
                    AYGlobal.updateUserModel(user)
                case .failure(_): break}
            })
            .disposed(by: disposeBag)
    }
}

public enum GlobalApi {
    
    /// 根据token校正客户端的用户对象
    case correctionuser
}

extension GlobalApi: AYTargetType {
    
    //请求路径
    public var path: String {
        switch self {
        case .correctionuser:
            return "user/correctionuser"
        }
    }
    
    //设置请求方式 get post等
    public var method: HTTPMethod {
        switch self {
        default:
            return .get
        }
    }
    
    /// 设置请求参数
    public var parameters: Parameters? {
        switch self {
        default:
            return nil
        }
    }
}
